<template>
  <div>
    <el-card class="box-card">
      <h2>客户列表</h2>
      <el-input
        v-model="searchName"
        placeholder="请输入客户名称"
        style="margin-bottom: 20px;"
      ></el-input>
      <el-button type="primary" @click="searchCustomer">查询</el-button>
      <el-table v-if="customers.length" :data="customers" style="width: 100%; margin-top: 20px;">
        <el-table-column prop="name" label="客户名称"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="address" label="地址" width="300"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="text" @click="editCustomer(scope.row)">编辑</el-button>
            <el-button type="text" @click="deleteCustomer(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-else style="text-align: center; margin-top: 20px;">
        没有找到匹配的客户
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchName: '',
      customers: [] // 确保初始化为数组
    };
  },
  mounted() {
    this.fetchCustomers();
  },
  methods: {
    fetchCustomers() {
      this.axios.get('/api/customer/get')
        .then(response => {
          const result = response.data;
          if (Array.isArray(result.data)) {
            this.customers = result.data; // 确保 customers 是数组
          } else {
            console.error('Error: Expected an array but got:', result.data);
          }
        })
        .catch(error => {
          console.error('Error fetching customers:', error);
        });
    },
    searchCustomer() {
      this.axios.get(`/api/customer/search?name=${this.searchName}`)
        .then(response => {
          const result = response.data;
          if (Array.isArray(result.data)) {
            console.log("Result data is an array:", result.data);
            this.customers = result.data; // 确保 customers 是数组
          } else {
            this.customers = []; // 如果没有匹配结果，清空 customers
            console.error('Error: Expected an array but got:', result);
          }
        })
        .catch(error => {
          this.customers = []; // 请求出错时也清空 customers
          console.error('Error searching customers:', error);
        });
    },
    editCustomer(customer) {
      console.log('编辑客户', customer);
      this.$router.push(`/customer/edit_customer2/${customer.name}`);
    },
    deleteCustomer(customer) {
      console.log('删除客户', customer);
      this.axios.delete(`/api/customer/delete/${customer.name}`)
        .then(() => {
          this.fetchCustomers(); // 删除后重新获取客户列表
        })
        .catch(error => {
          console.error('Error deleting customer:', error);
        });
    }
  }
}
</script>

<style scoped>
.box-card {
  margin: auto;
  width: 800px;
}
</style>
